#include "attackleases.h"

attackleases::attackleases(string filename)
{
    Storage=0;
    leasesFileName=filename;

    //Read leases file
    string line;
    ifstream myfile (leasesFileName.c_str());
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            //cout << line << endl;
            size_t found;
            found=line.find(" ");
            if ((int)found>0)
            {
                string IP=line.substr(0,found);
                string tms=line.substr(found+1);
                long tm=atol(tms.c_str());
                attackLeasesStructure temp;
                temp.IP=IP;
                temp.tm=tm;
                data.push_back(temp);
                Storage++;
            }
        }
        myfile.close();
    }

}

void attackleases::addLease(string IP, long tm)
{
    attackLeasesStructure temp;
    temp.IP=IP;
    temp.tm=tm;
    data.push_back(temp);

    //Write lease to file
    ofstream leasesfile;
    leasesfile.open (leasesFileName.c_str(), ios::out | ios::app);
    leasesfile << IP << " " << tm << endl;
    leasesfile.close();


    Storage++;
}

void attackleases::removeLease(int idx)
{
    if ( (idx>=0) && (idx<Storage))
    {
        attackLeasesStructure temp=data[idx];
        data.erase(data.begin()+idx);

        //Remove this lease from file also
        string ts="";
        string line;
        ifstream myfile (leasesFileName.c_str());
        if (myfile.is_open())
        {
            while ( myfile.good() )
            {
                getline (myfile,line);
                //cout << line << endl;
                size_t found;
                found=line.find(" ");
                if ((int)found>0)
                {
                    string IP=line.substr(0,found);
                    string tms=line.substr(found+1);
                    if (IP.compare(temp.IP)!=0)
                    {
                        if (ts.compare("")!=0)
                            ts=ts + "\n";
                        ts=ts+line;
                    }
                }
            }
            myfile.close();
            ofstream leasesfile;
            leasesfile.open (leasesFileName.c_str(), ios::out);
            leasesfile << ts << endl;
            leasesfile.close();
        }


        Storage--;
    }
}


attackleases::attackLeasesStructure attackleases::getLease(int idx)
{
    attackleases::attackLeasesStructure retVal;
    if ( (idx>=0) && (idx<Storage))
    {
        retVal=data[idx];
    }
    else
    {
        retVal.IP="";
        retVal.tm=0;
    }

    return retVal;

}

int attackleases::getLeasesSize()
{
    return (int)data.size();
}

int attackleases::leaseExist(string IP)
{
    int retVal=0;

    for (int i=0;i<(int)data.size();i++)
    {
        attackleases::attackLeasesStructure tIP=data[i];
        if (IP.compare(tIP.IP)==0)
        {
            retVal=1;
            break;
        }
    }

    return retVal;
}
